package com.ruicar.afs.cloud.channel.template.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.admin.api.dto.UserSimpleInfoDto;
import com.ruicar.afs.cloud.admin.api.feign.AfsUserFeign;
import com.ruicar.afs.cloud.channel.cardealer.common.Constants;
import com.ruicar.afs.cloud.channel.common.until.ChannelRoleEnum;
import com.ruicar.afs.cloud.channel.common.until.RoleTypeDic;
import com.ruicar.afs.cloud.channel.online.entity.ChannelBaseInfoTemp;
import com.ruicar.afs.cloud.channel.online.entity.ChannelRiskInfoTemp;
import com.ruicar.afs.cloud.channel.online.service.ChannelOnlineService;
import com.ruicar.afs.cloud.channel.online.service.ChannelRiskInfoService;
import com.ruicar.afs.cloud.channel.template.entity.ChannelSmsTemplate;
import com.ruicar.afs.cloud.channel.template.mapper.ChannelSmsTemplateMapper;
import com.ruicar.afs.cloud.channel.template.service.ChannelSmsTemplateService;
import com.ruicar.afs.cloud.channel.witness.entity.ChannelWitnessInfoTemp;
import com.ruicar.afs.cloud.channel.witness.utils.WitnessDic;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.MessageParamEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ResultBooleanEnum;
import com.ruicar.afs.cloud.message.sendmessage.config.MessageConfig;
import com.ruicar.afs.cloud.message.sendmessage.dto.MessageDataDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendMessageDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendResultInfoDto;
import com.ruicar.afs.cloud.message.sendmessage.service.MessageService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author Ices
 */
@Slf4j
@Service
@AllArgsConstructor
public class ChannelSmsTemplateServiceImpl extends ServiceImpl<ChannelSmsTemplateMapper, ChannelSmsTemplate> implements ChannelSmsTemplateService {
    private final AfsUserFeign afsUserFeign;
    private final ChannelOnlineService channelOnlineService;
    private final ChannelRiskInfoService channelRiskInfoService;
    private MessageService service;
    private MessageConfig messageConfig;



    @Override
    public void sendMessageByWitness(ChannelWitnessInfoTemp temp) {
        ChannelBaseInfoTemp b =channelOnlineService.getById(temp.getChannelId());
        // 直接查询出来这个合作商的 这个合作商的区域经理名字
        List<ChannelRiskInfoTemp> list =new ArrayList<>();
        IResponse<List<UserSimpleInfoDto>> user= new IResponse<>();
        if(WitnessDic.BUSINESS_ATTRIBUTES_NEW.equals(temp.getBusinessAttributes())){
            // 说明是新车  那么去找出来这个合作商的新车区域经理
            list=channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda().eq(ChannelRiskInfoTemp::getChannelId,temp.getChannelId()).eq(ChannelRiskInfoTemp::getBusinessType, RoleTypeDic.NEW_CAR));

            // 去找负责的渠道发展科员给他短信通知
            if(Constants.DIRECT.equals(b.getChannelBelong())){
                // 说明是直营
                user= afsUserFeign.getSimpleUserListByRoleCode(ChannelRoleEnum.ROLE_OWN_NEW_MANAGE_CHANNEL_DEVELOP.name());
            }else {
                user = afsUserFeign.getSimpleUserListByRoleCode(ChannelRoleEnum.ROLE_OTHER_NEW_MANAGE_CHANNEL_DEVELOP.name());
            }


        }else {
            // 说明是二手车  那么去找出来这个合作商的新车区域经理
            list=channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda().eq(ChannelRiskInfoTemp::getChannelId,temp.getChannelId()).eq(ChannelRiskInfoTemp::getBusinessType, RoleTypeDic.OLD_CAR));

            // 去找负责的渠道发展科员给他短信通知
            if(Constants.DIRECT.equals(b.getChannelBelong())){
                // 说明是直营
                user= afsUserFeign.getSimpleUserListByRoleCode(ChannelRoleEnum.ROLE_OWN_OLD_MANAGE_CHANNEL_DEVELOP.name());
            }else {
                user = afsUserFeign.getSimpleUserListByRoleCode(ChannelRoleEnum.ROLE_OTHER_OLD_MANAGE_CHANNEL_DEVELOP.name());
            }
        }
        if(list.size()>0){
            // 声明一个发短信的
            List<String>  name=new ArrayList<>();
            for (ChannelRiskInfoTemp t:list){
                if(t.getCustomerManager()!=null){
                    name.add(t.getCustomerManager());
                }
            }
            // 声明一个 手机号集合
            Set<String> phone=new HashSet<>();

            IResponse<List<UserSimpleInfoDto>> listIResponse = afsUserFeign.getSimpleInfoByUserLoginNames(name);
            if(CommonConstants.SUCCESS.equalsIgnoreCase(listIResponse.getCode())){
                List<UserSimpleInfoDto> c = JSON.parseArray(JSON.toJSONString(listIResponse.getData()), UserSimpleInfoDto.class);
                if(c.size()>0){
                    for ( UserSimpleInfoDto dto:c){
                        phone.add(dto.getPhone());

                    }
                }
            }
            if(CommonConstants.SUCCESS.equalsIgnoreCase(user.getCode())){
                List<UserSimpleInfoDto> u = JSON.parseArray(JSON.toJSONString(user.getData()), UserSimpleInfoDto.class);
                if(u.size()>0){
                    for ( UserSimpleInfoDto dto:u){
                        phone.add(dto.getPhone());
                    }
                }
            }

            if(phone.size()>0){
                for (String p :phone){
                    SendMessageDto messageDto= new SendMessageDto();
                    messageDto.setChannel("1");
                    messageDto.setCode(messageConfig.getCode());
                    messageDto.setTimestamp(System.currentTimeMillis()/1000+"");
                    messageDto.setUid(messageConfig.getUid());

                    List<MessageDataDto> dataDtoList=new ArrayList<>();
                    MessageDataDto dataDto= new MessageDataDto();
                    dataDto.setDeptId("003");
                    dataDto.setOrigin(messageConfig.getOrigin());
                    dataDto.setPhone(p);
                    //estimatedTime不传默认当晚上23:59失效
                         /*   dataDto.setEstimatedTime();*/
                    //防重复-一天重复发
                    SimpleDateFormat sd=new SimpleDateFormat("yyyyMMdd");
                    dataDto.setSummaryId(p+new Date().getTime());
                    dataDto.setSmsContent("你好,您管理的合作商正在重复备案。备案信息如下："+b.getChannelFullName()+"申请新车见证人:"+temp.getWitnessName()+",身份证号："+temp.getWitnessIdCard());
                    dataDto.setTemplateId("W101");
                    dataDto.setPriority("1");
                    dataDtoList.add(dataDto);

                    messageDto.setMessageDataDto(dataDtoList);
                    SendResultInfoDto sendResultInfoDto=service.sendMessageData(messageDto);
                    if(ObjectUtils.isNotEmpty(sendResultInfoDto)){
                        if(sendResultInfoDto.getResult().equals(ResultBooleanEnum.TRUE.getCode())){
                        }
                        else{
                            throw new AfsBaseException("见证人数据异常！");
                        }
                    }else{
                        throw new AfsBaseException("见证人异常！！");
                    }
                }
            }
        }

    }
}
